<script setup>
import { onMounted, reactive, ref, watch } from "vue"
import { deleteTableDataApi, getTableDataApi, saveTableDataApi } from "@/api/system/user"
import { ElMessage, ElMessageBox } from "element-plus"
import { Search, Refresh, CirclePlus, RefreshRight } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { cloneDeep } from "lodash-es"

defineOptions({
  // 命名当前组件
  name: "systemUser"
})

const loading = ref(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

//#region 增
const DEFAULT_FORM_DATA = {
  user_id: 0,
  username: "",
  password: "",
  name: "",
  mobile: "",
  is_admin: 20,
  is_use: 10
}

const validatePass = (rule, value, callback) => {
  console.log(rule, value, formData.value.user_id)
  if (value == "" && formData.value.user_id == 0) {
    callback(new Error(rule.message))
  } else {
    callback()
  }
}
const dialogVisible = ref(false)
const formRef = ref(null)
const formData = ref(cloneDeep(DEFAULT_FORM_DATA))
const formRules = {
  username: [{ required: true, trigger: "blur", message: "用户账号不能为空" }],
  password: [{ validator: validatePass, trigger: "blur", message: "登录密码不能为空" }]
}
const handleCreateOrUpdate = () => {
  formRef.value?.validate((valid, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    loading.value = true
    saveTableDataApi(formData.value)
      .then(() => {
        ElMessage.success("操作成功")
        dialogVisible.value = false
        getTableData()
      })
      .finally(() => {
        loading.value = false
      })
  })
}
const resetForm = () => {
  formRef.value?.clearValidate()
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
}
//#endregion

//#region 删
const handleDelete = (row) => {
  ElMessageBox.confirm(`正在删除用户：${row.username}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteTableDataApi({ id: row.user_id }).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//#endregion

//#region 改
const handleUpdate = (row) => {
  dialogVisible.value = true
  formData.value = cloneDeep(row)
}
//#endregion

//#region 查
const tableData = ref([])
const searchFormRef = ref(null)
const searchData = reactive({
  keyword: "",
})

const getTableData = () => {
  loading.value = true
  getTableDataApi({
    page: paginationData.currentPage,
    keyword:searchData.keyword,
  })
    .then((data) => {
      paginationData.total = data.total
      tableData.value = data.items
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}
//#endregion

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-form ref="searchFormRef" :inline="true" :model="searchData">
            <el-form-item prop="keyword" label="关键字">
              <el-input v-model="searchData.keyword" placeholder="请输入" />
            </el-form-item>
            <el-form-item>
              <el-button type="danger" :icon="Search" @click="handleSearch">查询</el-button>
              <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="CirclePlus" @click="dialogVisible = true">新增用户</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div>
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getTableData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData" border>
          <el-table-column prop="user_code" label="用户编码" align="left" />
          <el-table-column prop="username" label="用户名" align="left" />
          <el-table-column prop="is_admin" label="是否管理员" align="center" width="180">
            <template #default="scope">
              <el-tag v-if="scope.row.is_admin == 10" type="primary" effect="plain">是</el-tag>
              <el-tag v-else type="warning" effect="plain">否</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="姓名" align="center" width="180" />
          <el-table-column prop="mobile" label="手机" align="center" width="180" />
          <el-table-column prop="is_use" label="状态" width="80" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.is_use == 10" type="success" effect="plain">启用</el-tag>
              <el-tag v-else type="danger" effect="plain">禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button type="primary" bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="danger" bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination background :layout="paginationData.layout" :page-sizes="paginationData.pageSizes"
          :total="paginationData.total" :page-size="paginationData.pageSize" :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog v-model="dialogVisible" :title="formData.user_id === 0 ? '新增用户' : '修改用户'" @closed="resetForm"
      width="500px">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="username" label="用户账号" required>
          <el-input v-model="formData.username" placeholder="请输入用户账号" />
        </el-form-item>
        <el-form-item prop="password" label="登录密码" :required="formData.user_id == 0">
          <el-input v-model="formData.password" type="password" placeholder="请输入登录密码" />
        </el-form-item>
        <el-form-item prop="is_admin" label="是否管理员" required>
          <el-select v-model="formData.is_admin" placeholder="选择状态">
            <el-option label="普通用户" :value="20" />
            <el-option label="管理员" :value="10" />
          </el-select>
        </el-form-item>
        <el-form-item prop="is_use" label="状态" required>
          <el-select v-model="formData.is_use" placeholder="选择状态">
            <el-option label="启用" :value="10" />
            <el-option label="禁用" :value="20" />
          </el-select>
        </el-form-item>
        <el-form-item prop="user_code" label="用户编码" >
          <el-input v-model="formData.user_code" :disabled="formData.user_id !== 0  && formData.user_code != ''" placeholder="请输入用户编码" />
        </el-form-item>
        <el-form-item prop="name" label="用户姓名">
          <el-input v-model="formData.name" placeholder="请输入用户姓名" />
        </el-form-item>
        <el-form-item prop="mobile" label="联系手机">
          <el-input v-model="formData.mobile" placeholder="请输入联系手机" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreateOrUpdate" :loading="loading">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;

  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
